package com.wenhua.junshao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenhua.junshao.dot.DishDto;
import com.wenhua.junshao.entity.Dish;
import com.wenhua.junshao.entity.DishFlavor;
import com.wenhua.junshao.mapper.DishMapper;
import com.wenhua.junshao.service.DishFlavorService;
import com.wenhua.junshao.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;


    /**
     * 新增菜品
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息

        this.save(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();
        //设置菜品与口味

        flavors.forEach(flavor -> flavor.setDishId(dishDto.getId()));

        //保存菜品口味数据到菜品口味表中
        dishFlavorService.saveBatch(flavors);
    }

    //菜品修改数据回显
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息，从dish表查询
        Dish dish = this.getById(id);
        //查询菜品口味
        LambdaQueryWrapper<DishFlavor> wrapper = Wrappers.lambdaQuery(DishFlavor.class)
                .eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        DishDto dishDto = new DishDto();

        //复制信息
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(list);

        return dishDto;

    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        dishService.updateById(dishDto);
        //清理当前菜品对应的口味信息
     
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //重新封装数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);


    }


}
